# idx2numLst.py
from mapping.numLst2idx import GuaConverter
from constants import GUA_NAME_LST, NATURE_TO_PROJECT_GUA_IDX, FIX_LST


def _get_num_lst(idx: int = None, gua_name: str = None, is_nature: bool = False) -> list[int] | None:
    """
    根据卦名或卦序号获取数字列表
    :param gua_name: 卦名
    :param idx: 卦序号
    :param is_nature: 是否为自然卦序号
    :return: 数字列表
    """

    def score(condition):
        return 2 if condition else 1

    if idx is None:
        if gua_name is None:
            print('必须提供卦名或卦序号')
            return
        name = gua_name.strip(FIX_LST)
        if name not in GUA_NAME_LST:
            print('不合规的卦名', name)
            return
        idx = GUA_NAME_LST.index(name)
    else:
        if isinstance(idx, str) and idx.isdigit():
            try:
                idx = int(idx)
            except ValueError:
                print('不合规的卦序号', idx, type(idx))
                return
        if not isinstance(idx, int) or idx >= 64 or idx <= -1:
            print('不合规的卦序号', idx, type(idx))
            return
        if not is_nature:
            idx = NATURE_TO_PROJECT_GUA_IDX.index(idx)

    return [score(idx % 2 == 1), score(idx % 4 >= 2), score(idx % 8 >= 4),
            score(idx % 16 >= 8), score(idx % 32 >= 16), score(idx >= 32)]


def _get_num_lst_from_pair(gua_idx, biangua_idx: int = None) -> list[int]:
    if not isinstance(gua_idx, int) or gua_idx < 0 or gua_idx >= 64:
        raise ValueError('不合规的卦序号', gua_idx, type(gua_idx))

    if biangua_idx is None or gua_idx == biangua_idx:
        return _get_num_lst(idx=gua_idx)
    else:
        gualst = _get_num_lst(idx=gua_idx)
        bianlst = _get_num_lst(idx=biangua_idx)
        _map = {1: 3, 2: 0}
        return [g if g == b else _map[g] for g, b in zip(gualst, bianlst)]


'''此为示例用法，可不用'''
class GuaFactory:
    @staticmethod
    def from_gua_name(gua_name: str) -> GuaConverter:
        """
        根据卦名创建 GuaConverter 实例
        :param gua_name: 卦名
        :return: GuaConverter 实例
        """
        return GuaConverter(_get_num_lst(gua_name=gua_name))

    @staticmethod
    def from_gua_idx(idx: int) -> GuaConverter:
        """
        根据卦序号创建 GuaConverter 实例
        :param idx: 卦序号
        :return: GuaConverter 实例
        """
        return GuaConverter(_get_num_lst(idx=idx))


if __name__ == '__main__':
    print('卦名', '项目卦序号', '自然卦序号', '八纯卦序号')
    for gua in GUA_NAME_LST:
        gf = GuaFactory.from_gua_name(gua)
        print(gua, gf.get_gua_idx(), gf.get_nature_idx(), gf.get_home_idx())
